﻿using System.Collections.Generic;
using System.Linq;
using VotesResults.Models;

namespace VotesResults.Daos.EntityFramework
{
    public class VoteDao : IVoteDao
    {
        public List<Vote> Load()
        {
            using (VotesResultsEntities db = new VotesResultsEntities())
                return db.Vote.ToList();
        }

        public Vote Get(int id)
        {
            using (VotesResultsEntities db = new VotesResultsEntities())
                return db.Vote.FirstOrDefault(m => m.Id == id);
        }

        public void Add(Vote vote)
        {
            using (VotesResultsEntities db = new VotesResultsEntities())
            {
                db.AddToVote(vote);
                db.SaveChanges();
            }
        }

        public void Update(Vote vote)
        {
            using (VotesResultsEntities db = new VotesResultsEntities())
            {
                Vote record = db.Vote.FirstOrDefault(m => m.Id == vote.Id);
                if (record != null)
                {
                    record.Name = vote.Name;
                    record.Description = vote.Description;
                }
                db.SaveChanges();
            }
        }

        public void Remove(int id)
        {
            using (VotesResultsEntities db = new VotesResultsEntities())
            {
                Vote vote = db.Vote.FirstOrDefault(m => m.Id == id);
                if (vote != null)
                {
                    db.DeleteObject(vote);
                    db.SaveChanges();
                }
            }
        }
    }
}